package net.lastcoder.tools.fileupload;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

/**
 * auth: WenYF
 * date: 2017/4/2 0002
 */
public class FileUpload {

    public static final void main(String[] args) {
        System.out.println("fileupload...");
        String addr = args[0];
        String filePath = args[1];
        HashMap<String, String> headers = new HashMap<>();
        if (args.length >= 2) {
            for (int i = 2; i < args.length; i++) {
                String[] splits = args[i].split(":");
                headers.put(splits[0], splits[1]);
            }
        }
        System.out.println("url=" + addr);
        System.out.println("filePath=" + filePath);
        new net.lastcoder.tools.fileupload.FileUpload(addr, filePath, headers);
    }

    FileUpload(String addr, String filePath, HashMap<String, String> headers) {
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("file not exist.");
            return;
        }

        String md5 = Md5.sum(file.getAbsolutePath());
        try {
            URL url = new URL(addr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("md5", md5);
            connection.setRequestProperty("filename", file.getName());

            if (headers != null && headers.size() > 0) {
                for (String key : headers.keySet()) {
                    connection.setRequestProperty(key, headers.get(key));
                }
            }

            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(5000);
            connection.connect();
            OutputStream os = connection.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[fis.available()];
            int size = fis.read(buffer);
            os.write(buffer, 0, size);

            fis.close();
            os.close();

            InputStream is = connection.getInputStream();

            StringBuilder sb = new StringBuilder();
            byte[] readBuffer = new byte[1024];
            while ((size = is.read(readBuffer)) != -1) {
                for (int i = 0; i < size; i++) {
                    sb.append((char)readBuffer[i]);
                }
            }

            System.out.println("code:" + connection.getResponseCode()
                    + ",msg=" + connection.getResponseMessage());
            System.out.println("content:" + sb.toString());

            connection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
